# 测试对话历史持久化存储功能
import sys
sys.stdout.reconfigure(encoding='utf-8')

from main import KnowledgeExplanationAgent
import os
import json

def test_persistent_storage():
    print("=== 测试对话历史持久化存储功能 ===")
    
    # 创建智能体实例
    agent = KnowledgeExplanationAgent()
    user_id = "persistent_test_user"
    
    print("\n1. 发送测试问题:")
    test_questions = [
        "你好",
        "什么是所有权？",
        "如何使用Vec？"
    ]
    
    for i, question in enumerate(test_questions, 1):
        print(f"\n问题 {i}: {question}")
        result = agent.process_question(user_id, question)
        
        if result['status'] == 'success':
            print(f"分类: {result['classification']['label']}")
            print(f"回答长度: {len(result['answer_markdown'])}")
        else:
            print(f"错误: {result['message']}")
    
    print("\n2. 检查存储统计:")
    stats = agent.context_manager.get_storage_stats()
    print(f"存储目录: {stats['storage_dir']}")
    print(f"总会话数: {stats['total_sessions']}")
    print(f"总大小: {stats['total_size_mb']} MB")
    
    print("\n3. 检查会话文件:")
    session_file = os.path.join(stats['storage_dir'], f"{user_id}.json")
    if os.path.exists(session_file):
        print(f"会话文件存在: {session_file}")
        with open(session_file, 'r', encoding='utf-8') as f:
            session_data = json.load(f)
        print(f"文件中的对话轮次: {len(session_data.get('context', []))}")
    else:
        print("会话文件不存在")
    
    print("\n4. 创建新的智能体实例测试加载:")
    # 创建新的智能体实例来测试加载功能
    new_agent = KnowledgeExplanationAgent()
    context = new_agent.context_manager.get_context(user_id)
    print(f"新实例加载的对话轮次: {len(context)}")
    
    if context:
        print("历史对话内容:")
        for i, turn in enumerate(context, 1):
            print(f"  轮次 {i}: {turn['question']} -> {turn['classification']['label']}")
    
    print("\n=== 测试完成 ===")

if __name__ == "__main__":
    test_persistent_storage()


